<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use App\Models\Position;
use App\Models\PositionTranslation;
use App\Services\QiniuServices;
use DB;
class PositionController extends AdminController
{
	private $sid;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.position.index');
    }


    public function data(Request $request)
    {
        $lang  = $request->lang??lang();
        $title = $request->get('title');
        $model = PositionTranslation::query();
        $model = $model->where('locale',$lang);
        if ($title) {
            $model = $model->where('title', 'like', '%' . $title . '%');
        }


        $res = $model->where('pid',0)->orderBy('id', 'desc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return response()->json($data);
    }
    

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.position.create', compact('positions'));
    }

 

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $data = $request->all();
        DB::beginTransaction();
         try {

            $Position = new Position();
            $Position->classname = $request->classname??$request->title;
            $Position->tag = $request->tag;
            $this->sid = PositionTranslation::max('sid');
            $Position->status = 1;
 
       
            foreach (config('translatable.locales') as $locale => $item) {
                
                
               
             }
            $Position->save();
            DB::commit();

            return Response::json(['code' => 0, 'msg' => '添加成功', 'data' => '添加成功', 'url' => route('admin.ad')]);

          } catch (\Exception $exception) {
            DB::rollback();

        }


        return response()->json(['code' => 0, 'msg' => '系统错误']);
    }

 


    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request)
    {
        $id = (int)$request->get('id');
         $position = PositionTranslation::with('advname')->findOrFail($id);
        //所有广告位置
        $positions = $this->getPositionClass();
        return view('admin.position.edit', compact('positions', 'position'));
    }





    /**
     * 广告位更新
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $id = (int)$request->get('id');
        if(empty($id))  return Response::json(['code' => 1, 'msg' => '非法操作']);

        $data = $request->except(['_token', 'file']);
        $request = (object)$data;

        DB::beginTransaction();
        try {
            $PositionTranslation = PositionTranslation::findOrFail($id);
           
            $Position = Position::whereTranslation('id', $id)->firstOrFail();
            $Position->classname = $request->title;
            foreach (config('translatable.locales') as $locale => $item) {
                
                
				if(!$Position->hasTranslation($locale)){

					$Position = $this->createItem($Position,$request,$locale);
					
					$Position->translateOrNew($locale)->sid = $PositionTranslation->sid;
					$Position->translateOrNew($locale)->pid = $PositionTranslation->pid;
				 
				}
				
				
            }
           
           $Position->save(); 
           $PositionTranslation->update($data);
 
           DB::commit();
           return response()->json(['code' => 0, 'msg' => '更新成功']);
        
      } catch (\Exception $exception) {
        DB::rollback();
      }
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

 


    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = (array)$request->get('ids');
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
		$qiniu = new QiniuServices();

        DB::beginTransaction();
        //try {
            
			foreach($ids as $id){
				$Position = Position::whereTranslation('id', $id)->firstOrFail();
				foreach($Position->translations as $item){
					 
					//检查广告位下是否有 广告
					$advCount = Position::whereTranslation('pid', $item->sid)->count();
					 
					if($advCount){
						
						$advPosition = Position::whereTranslation('pid', $item->sid)->firstOrFail();
						
						foreach($advPosition->translations as $obj){
							//删除云端资源
							$qiniu->objFromDelete($obj);
						}
						$advPosition->deleteTranslations();
						$advPosition->delete();
					}

				}
				$Position->delete();
				
				
			}
			
			
			
			DB::commit();
			return response()->json(['code' => 0, 'msg' => '删除成功']); 
       // } catch (\Exception $exception) {
            DB::rollback();
       // }

        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }


 



	private function createItem($Position,$request,$locale){
		
			//新增时此时需要设置
			if(isset($this->sid)) $Position->translateOrNew($locale)->sid = $this->sid + 1;
			 
				
				$Position->translateOrNew($locale)->pid = $request->pid;
				$Position->translateOrNew($locale)->type = $request->type;
				$Position->translateOrNew($locale)->title = $request->title;
				$Position->translateOrNew($locale)->firsttitle = $request->firsttitle??'';
				$Position->translateOrNew($locale)->secondtitle = $request->secondtitle??'';
				$Position->translateOrNew($locale)->thirdtitle = $request->thirdtitle??'';
				$Position->translateOrNew($locale)->keywords = $request->keywords??'';
				$Position->translateOrNew($locale)->description = $request->description??'';
				$Position->translateOrNew($locale)->thumb = $request->thumb??'';
				$Position->translateOrNew($locale)->body = $request->body??'';
				$Position->translateOrNew($locale)->sort = $request->sort??255;
				$Position->translateOrNew($locale)->remarks = $request->remarks;
				 
			return $Position;
	}

    public function getPositionClass(){

     return  PositionTranslation::where('pid',0)->where('locale',lang())->get();

    }

}
